from functools import update_wrapper
from django.http.response import HttpResponse
from utility.firepark_time import get_datetime_mysql
from firepark_admin.models import Userinfo, use_records, park_info, parking_lot, Spaces
from collections import Counter
import datetime

"""

来到停车场之前要查该停车场里有没有空位，

显示屏的上显示的状态

进入后，记录表更新开始时间，停车位的标志更改一下


出去后，记录表更新出去时间，
计算收费金额，
更新车位状态，
更新显示屏的状态

"""
PER_MINUTE_FEE = 0.1
MAX_FEE = 50
ALLOW_MINUTES = 5


# 当前停车位是否有空，要传入停车场id
def parking_lot_available(park_id):
    return parking_lot.objects.filter(park_id__exact=park_id, flag=True).exists()


# 当前停车位是否有空，要传入停车场id, 详细信息
def parking_lot_available_details(park_id):
    unuses = parking_lot.objects.filter(park_id__exact=park_id, flag=True)
    parts = []
    for unuse in unuses:
        parts.append(unuse.part)
    return Counter(parts)


# 进入，要传入车牌号,停车场id
def in_park(park_id, plate_number):
    """
    总之，一共有四种方法
    # 方法 1
    Author.objects.create(name="WeizhongTu", email="tuweizhong@163.com")

    # 方法 2
    twz = Author(name="WeizhongTu", email="tuweizhong@163.com")
    twz.save()

    # 方法 3
    twz = Author()
    twz.name="WeizhongTu"
    twz.email="tuweizhong@163.com"
    twz.save()

    # 方法 4，首先尝试获取，不存在就创建，可以防止重复
    Author.objects.get_or_create(name="WeizhongTu", email="tuweizhong@163.com")
    # 返回值(object, True/False)

    lot_id = models.IntegerField(verbose_name='车位id')
    flag=models.BooleanField(verbose_name='状态', default=True)
    part=models.CharField(verbose_name='区域',max_length=11)
    create_time=models.DateTimeField(verbose_name='创建时间')
    update_time=models.DateTimeField(verbose_name='更新时间')
    park_id=models.IntegerField(verbose_name='停车场id')

        """
    # 先插入一个进入的记录，之后计算通过fee为0来判断
    time = get_datetime_mysql()
    ur = use_records(plate_number=plate_number, in_time=time, out_time=time, park_id=park_id, fee=0)
    ur.save()


# 这里就通过传感器触发来修改
def parking_lot_update(park_id, lot_id, flag):
    # 修改停车位
    time = get_datetime_mysql()
    # parking_lot.objects.filter(park_id=park_id,lot_id=lot_id).update(flag=False, update_time=time)
    pl = parking_lot.objects.get(park_id=park_id, lot_id=lot_id)
    pl.flag = flag
    pl.update_time = time
    pl.save()  # 最后不要忘了保存！！！


# 获得费用
def get_fee(in_time, out_time, vip_status):
    diff = out_time - in_time
    seconds = diff.seconds
    minutes = seconds / 60
    fee = int(minutes) * PER_MINUTE_FEE
    if minutes <= ALLOW_MINUTES:
        fee = 0
    if fee >= MAX_FEE:
        fee = MAX_FEE
    if vip_status == 1:
        fee = fee * 0.95
    if vip_status == 2:
        fee = fee * 0.9
    if vip_status == 3:
        fee = fee * 0.8
    return fee

